package leetcode.LinkedList;

/**
 * @author MaoLin Wang
 * @date 2020/2/1015:10
 */
public class _02AddTwoNumbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(0);
        ListNode tempNode = result;
        int jinwei = 0;
        ListNode temp1 = l1;
        ListNode temp2 = l2;
        while (temp1 != null || temp2 != null) {
            int val1 = (temp1 != null) ? temp1.val : 0;
            int val2 = (temp2 != null) ? temp2.val : 0;
            int sum = jinwei + val1 + val2;
            jinwei = sum / 10;
            tempNode.next = new ListNode(sum % 10);
            tempNode = tempNode.next;
            if (temp1 != null) {
                temp1 = temp1.next;
            }
            if (temp2 != null) {
                temp2 = temp2.next;
            }
        }
        if (jinwei > 0) {
            tempNode.next = new ListNode(jinwei);
        }
        return result.next;
    }


    /**
     * 关键点：数字在链表中是倒序的，因此按顺序进行相加就是从个位开始计算的
     *        需要考虑进位：每次相加要额外添加上一个的进位，然后更新进位：sum/10，此次求和去掉进位的值为 sum%10
     *        当两个链表都遍历完了，还需看下进位是否大于0，如果大于0还要将进位放到尾节点
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode result=new ListNode(0);
        ListNode temp1=l1;
        ListNode temp2=l2;

        ListNode tempResult=result;

        int up=0;

        while (temp1!=null || temp2!=null){
            int v1 = temp1 == null ? 0 : temp1.val;
            int v2 = temp2 == null ? 0 : temp2.val;
            int sum=v1+v2+up;

            up=sum/10;

            tempResult.next=new ListNode(sum%10);
            tempResult=tempResult.next;

            if (temp1!=null){
                temp1=temp1.next;
            }
            if (temp2!=null){
                temp2=temp2.next;
            }
        }
        if (up>0){
            tempResult.next=new ListNode(up);
        }
        return result.next;

    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(0);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
        l1.next.next.next = new ListNode(3);
        ListNode l2 = new ListNode(0);
        l2.next = new ListNode(5);
        l2.next.next = new ListNode(6);
        l2.next.next.next = new ListNode(4);
        ListNode listNode = addTwoNumbers(l1.next, l2.next);
        System.out.println(listNode.toString());
    }
}
